public class HashBuck {

    static class Node {
       public int key;
       public int value;
       public Node next;
       public Node(int key,int value) {
           this.key = key;
           this.value = value;
       }
    }

    public Node[] array;
    public int usedSize;

    public static final double LOAD_FACTOR = 0.75;

    public HashBuck() {
        array = new Node[10];
    }

    public void put(int key,int value) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                cur.value  =value;
                return ;
            }
            cur = cur.next;
        }
        //用头插法插入
        Node node = new Node(key,value);
        node.next = array[index];
        array[index] = node;
        usedSize++;
        //扩容操作
        if (calculateLoadFactor() >= LOAD_FACTOR) {
            resize();
        }
    }

    private void resize() {
        Node[] newArray = new Node[2 * array.length];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                Node curNext = cur.next;
                //重新计算哈希地址
                int index = cur.key % newArray.length;
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = curNext;
            }
        }
        array = newArray;
    }

    private double calculateLoadFactor() {
        return usedSize * 1.0 / array.length;
    }
   public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                return cur.value;
            }
            cur = cur.next;
        }
        return -1;
   }
}
